import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Table, 
  Button, 
  Space, 
  Popconfirm, 
  message, 
  Input, 
  Row, 
  Col,
  Typography,
  Tag
} from 'antd';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  SearchOutlined 
} from '@ant-design/icons';
import FurnitureForm from '../components/FurnitureForm';
import { furnitureService } from '../services/furnitureService';
import { categoryService } from '../services/categoryService';

const { Title } = Typography;
const { Search } = Input;

const FurnitureManagement = () => {
  const [furniture, setFurniture] = useState([]);
  const [categories, setCategories] = useState([]);
  const [loading, setLoading] = useState(false);
  const [formVisible, setFormVisible] = useState(false);
  const [editingFurniture, setEditingFurniture] = useState(null);
  const [searchText, setSearchText] = useState('');

  // 获取家具列表
  const fetchFurniture = async () => {
    try {
      setLoading(true);
      const response = await furnitureService.getAllFurniture();
      setFurniture(response.data);
    } catch (error) {
      message.error('获取家具列表失败');
      console.error('获取家具列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 获取分类列表
  const fetchCategories = async () => {
    try {
      const response = await categoryService.getAllCategories();
      setCategories(response.data);
    } catch (error) {
      console.error('获取分类列表失败:', error);
    }
  };

  useEffect(() => {
    fetchFurniture();
    fetchCategories();
  }, []);

  // 创建家具
  const handleCreate = async (furnitureData) => {
    try {
      await furnitureService.createFurniture(furnitureData);
      message.success('家具创建成功');
      setFormVisible(false);
      fetchFurniture();
    } catch (error) {
      message.error('创建家具失败');
      console.error('创建家具失败:', error);
    }
  };

  // 更新家具
  const handleUpdate = async (furnitureData) => {
    try {
      await furnitureService.updateFurniture(editingFurniture.id, furnitureData);
      message.success('家具更新成功');
      setFormVisible(false);
      setEditingFurniture(null);
      fetchFurniture();
    } catch (error) {
      message.error('更新家具失败');
      console.error('更新家具失败:', error);
    }
  };

  // 删除家具
  const handleDelete = async (id) => {
    try {
      await furnitureService.deleteFurniture(id);
      message.success('家具删除成功');
      fetchFurniture();
    } catch (error) {
      message.error('删除家具失败');
      console.error('删除家具失败:', error);
    }
  };

  // 打开创建表单
  const openCreateForm = () => {
    setEditingFurniture(null);
    setFormVisible(true);
  };

  // 打开编辑表单
  const openEditForm = (furniture) => {
    setEditingFurniture(furniture);
    setFormVisible(true);
  };

  // 获取分类名称
  const getCategoryName = (categoryId) => {
    const category = categories.find(cat => cat.id === categoryId);
    return category ? category.name : '未知分类';
  };

  // 过滤家具
  const filteredFurniture = furniture.filter(item =>
    item.name.toLowerCase().includes(searchText.toLowerCase()) ||
    item.description?.toLowerCase().includes(searchText.toLowerCase())
  );

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      render: (price) => `¥${price}`,
      sorter: (a, b) => a.price - b.price,
    },
    {
      title: '库存',
      dataIndex: 'stock',
      key: 'stock',
      render: (stock) => (
        <Tag color={stock > 10 ? 'green' : stock > 0 ? 'orange' : 'red'}>
          {stock}
        </Tag>
      ),
      sorter: (a, b) => a.stock - b.stock,
    },
    {
      title: '分类',
      dataIndex: 'categoryId',
      key: 'categoryId',
      render: (categoryId) => getCategoryName(categoryId),
    },
    {
      title: '操作',
      key: 'actions',
      width: 150,
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => openEditForm(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个家具吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div className="page-content">
      <div className="page-header">
        <Title level={2}>家具管理</Title>
      </div>
      
      <Card className="card-container">
        <Row justify="space-between" align="middle" style={{ marginBottom: 16 }}>
          <Col>
            <Search
              placeholder="搜索家具名称或描述"
              allowClear
              style={{ width: 300 }}
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              prefix={<SearchOutlined />}
            />
          </Col>
          <Col>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={openCreateForm}
            >
              新增家具
            </Button>
          </Col>
        </Row>

        <Table
          columns={columns}
          dataSource={filteredFurniture}
          rowKey="id"
          loading={loading}
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
        />
      </Card>

      <FurnitureForm
        visible={formVisible}
        onCancel={() => {
          setFormVisible(false);
          setEditingFurniture(null);
        }}
        onSubmit={editingFurniture ? handleUpdate : handleCreate}
        furniture={editingFurniture}
        title={editingFurniture ? '编辑家具' : '新增家具'}
      />
    </div>
  );
};

export default FurnitureManagement;
